package com.briup.web;

import com.alibaba.excel.EasyExcel;
import com.briup.bean.DemoData;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/file")
public class FileController {
    @GetMapping("dwownload")
    public void download(HttpServletResponse resp) throws IOException {

        // 这里注意 有同学反应使用swagger 会导致各种问题，请直接用浏览器或者用postman
        resp.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        resp.setCharacterEncoding("utf-8");
        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        String fileName = URLEncoder.encode("测试", "UTF-8").replaceAll("\\+", "%20");
        resp.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");

    //将生成的excel字节信息写出响应响应体
        ServletOutputStream out = resp.getOutputStream();
        EasyExcel.write(out, DemoData.class).sheet().doWrite(data());
    }
    public List<DemoData> data(){
        ArrayList<DemoData> list = new ArrayList<>();
        for (int i = 0; i < 5; i++) {
            //1.构造器 、2set lombok 链式调用 3.builder
            DemoData data = new DemoData();
            data.setDoubleData(1.2);
            data.setName("jackk");
            list.add(data);
        }
        return list;

    }
}